package be.idamf.mx.validation
{
	import mx.collections.ArrayList;
	import mx.core.IMXMLObject;
	import mx.validators.Validator;

	[DefaultProperty("validators")]
	public class Validation implements IMXMLObject
	{
		////////////////////////////////////////////////////////////////////////
		// Properties
		
		[ArrayElementType("mx.validators.Validator")]
		[Bindable]
		public var validators:Array;
		
		[Bindable]
		public var editor:Object;
		
		////////////////////////////////////////////////////////////////////////
		// Constructor
		
		public function Validation()
		{
		}
		
		////////////////////////////////////////////////////////////////////////
		// Accessors
		
		private var _source:Object;
		[Bindable]
		public function get source():Object
		{
			return _source;
		}
		public function set source(value:Object):void
		{
			_source = value;
			clean();
		}
		
		private var _isValid:Boolean
		[Bindable]
		public function get isValid():Boolean
		{
			return _isValid;
		}
		protected function set isValid(value:Boolean):void
		{
			_isValid = value;
		}

		private var _errors:ArrayList
		[Bindable]
		public function get errors():ArrayList
		{
			return _errors;
		}
		protected function set errors(value:ArrayList):void
		{
			_errors = value;
		}
		
		////////////////////////////////////////////////////////////////////////
		// Methods
		
		public function clean():void
		{
			var validator:Validator;
			
			if (!editor)
				return;
			
			for each (validator in validators)
			{
				if (editor.hasOwnProperty(validator.property + "Field"))
				{
					editor[validator.property + "Field"].errorString = "";
				}
			}
		}
		
		public function execute():void
		{
			var validator:Validator;
			
			if (!source)
			{
				throw new Error("No source defined.");
			}
			
			for each (validator in validators)
			{
				validator.source = source;
				
				if (editor && editor.hasOwnProperty(validator.property + "Field"))
				{
					validator.listener = editor[validator.property + "Field"];
				}
				else
				{
					validator.listener = null;
				}
			}
			
			errors = new ArrayList(Validator.validateAll(validators));
			isValid = (errors.length == 0);
		}
		
		////////////////////////////////////////////////////////////////////////
		// IMXMLObject impl
		
		public function initialized(document:Object, id:String):void
		{
			if (!editor)
				editor = document;
		}
	}
}